package com.shycloud.mido.member.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happy.zebra.admin.api.entity.SysActLogZebra;
import com.happy.zebra.admin.api.feign.AdminFeignService;
import com.joy.zebra.common.push.JPushUtils;
import com.shycloud.mido.common.api.entity.OrganizationCommon;
import com.shycloud.mido.common.api.mapper.OrganizationCommonMapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.constant.SecurityConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.common.sms.sdk.CloopenSmsSDK;
import com.shycloud.mido.homework.api.enums.JPushCodeEnum;
import com.shycloud.mido.member.api.dto.MemberV2DTO;
import com.shycloud.mido.member.api.dto.MidoMasterDTO;
import com.shycloud.mido.member.api.dto.OrgDto;
import com.shycloud.mido.member.api.entity.ErpActivityInfo;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MemberActivateEntity;
import com.shycloud.mido.member.api.entity.MemberDetailInfo;
import com.shycloud.mido.member.api.entity.MemberRole;
import com.shycloud.mido.member.api.entity.MsgMain;
import com.shycloud.mido.member.api.entity.MultiStudentClassroomLink;
import com.shycloud.mido.member.api.entity.MultiTeacherClassroomLink;
import com.shycloud.mido.member.api.entity.OptOrg;
import com.shycloud.mido.member.api.entity.OrgOrganization;
import com.shycloud.mido.member.api.entity.OrgStudentDetailed;
import com.shycloud.mido.member.api.entity.OrgTeacherDetailed;
import com.shycloud.mido.member.api.entity.OrgTeacherStudent;
import com.shycloud.mido.member.api.entity.SmMemberDel;
import com.shycloud.mido.member.api.entity.SmMemberPlayRewardInfo;
import com.shycloud.mido.member.api.entity.SmMemberTeacherApprovalNew;
import com.shycloud.mido.member.api.entity.StudentPlayTimeDaily;
import com.shycloud.mido.member.api.entity.SysUser;
import com.shycloud.mido.member.api.entity.SysUserRole;
import com.shycloud.mido.member.api.feign.MasterFeignService;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.vo.*;
import com.shycloud.mido.member.mapper.ErpActivityInfoMapper;
import com.shycloud.mido.member.mapper.MemberActivateMapper;
import com.shycloud.mido.member.mapper.MemberDetailInfoMapper;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MemberRoleMapper;
import com.shycloud.mido.member.mapper.MultiStudentClassroomLinkMapper;
import com.shycloud.mido.member.mapper.MultiTeacherClassroomLinkMapper;
import com.shycloud.mido.member.mapper.OptOrgMapper;
import com.shycloud.mido.member.mapper.OrgStudentDetailedMapper;
import com.shycloud.mido.member.mapper.OrgTeacherDetailedMapper;
import com.shycloud.mido.member.mapper.OrgTeacherStudentMapper;
import com.shycloud.mido.member.mapper.SmMemberDelMapper;
import com.shycloud.mido.member.mapper.SmMemberPlayRewardInfoMapper;
import com.shycloud.mido.member.mapper.SmMemberTeacherApprovalNewMapper;
import com.shycloud.mido.member.mapper.StudentPlayTimeDailyMapper;
import com.shycloud.mido.member.mapper.SysUserMapper;
import com.shycloud.mido.member.mapper.SysUserRoleMapper;
import com.shycloud.mido.member.service.*;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.organ.api.enums.MessageCodeEnum;
import com.shycloud.mido.organ.api.feign.RemoteOrganService;
import java.time.ZoneOffset;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理
 *
 * @author nianhua.jiang
 * @date 2021-06-10 10:01
 */
@Service
@AllArgsConstructor
public class MemberServiceImplV2 extends ServiceImpl<MemberMapper, Member> implements
		MemberServiceV2 {

	/** 会员模块 mapper */
	private final MemberMapper memberMapper;
	/** 会员详细信息 mapper */
	private final MemberDetailInfoMapper memberDetailInfoMapper;
	/** 工作室 mapper */
	private final OrganizationCommonMapper organizationCommonMapper;
	/** 会员身份 mapper */
	private final MemberRoleMapper memberRoleMapper;
	/** 教师认证 mapper */
	private final SmMemberTeacherApprovalNewMapper teacherApprovalMapper;
	/** 学生信息 mapper */
	private final OrgStudentDetailedMapper studentMapper;
	/** 后台管理系统 用户 mapper */
	private SysUserMapper sysUserMapper;
	/** 后台管理系统 用户-角色 mapper */
	private SysUserRoleMapper sysUserRoleMapper;
	/** 师生关系 mapper */
	private OrgTeacherStudentMapper teacherStudentMapper;
	/** 教师模块 mapper */
	private final OrgTeacherDetailedMapper teacherDetailedMapper;
	/** 打印活动 mapper */
	private final ErpActivityInfoMapper activityInfoMapper;
	/** 学生每日探亲时长 mapper */
	private StudentPlayTimeDailyMapper studentPlayTimeDailyMapper;
	/** 学生每日练琴时长 mapper */
	private SmMemberPlayRewardInfoMapper smMemberPlayRewardInfoMapper;

	private OptOrgMapper optOrgMapper;

	/** 教师 service */
	private TeacherService teacherService;
	/** 每日训练时长奖励 模块 mapper */
	private SmMemberPlayRewardInfoMapper rewardInfoMapper;
	/** 纠错大师 激活模块 service */
	private MemberActivateMapper memberActivateMapper;
	/** 推送消息模块 service */
	private MsgMainService msgMainService;
	/** 推送消息详情 service */
	private MsgMemberInfoService msgMemberInfoService;
	/** VIP 模块 service */
	private VipMemberService vipMemberService;

	/** feign organ 服务 service */
	private RemoteOrganService remoteOrganService;
	/** feign 纠错大师 服务 service */
	private MasterFeignService masterFeignService;
	/** admin 模块 feign */
	private final AdminFeignService adminFeignService;
	//private final RedissonClient redissonClient;

	/** 学生身份 */
	private final String IDENTITY_STUDENT = "0";
	/** 教师身份 */
	private final String IDENTITY_TEACHER = "1";

	/** paramter 参数：orgId */
	private static final String PARAM_ORG_ID = "orgId";
	/** paramter 参数：teacherMemberId */
	private static final String PARAM_TEACHER_MEMBER_ID = "teacherMemberId";
	/** paramter 参数：studentMemberId */
	private static final String PARAM_STUDENT_MEMBER_ID = "studentMemberId";
	/** paramter 参数：teacherUsername */
	private static final String PARAM_TEACHER_USERNAME = "teacherUsername";
	/** paramter 参数：studentUsername */
	private static final String PARAM_STUDENT_USERNAME = "studentUsername";
	/** paramter 参数：identity */
	private static final String PARAM_IDENTITY = "identity";

	/** 密码加密 */
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
	/** redis 服务 */
	private RedisTemplate redisTemplate;
	/** 短信接口 */
	private CloopenSmsSDK cloopenSmsSDK;

	private SmMemberDelMapper delLogMapper;

	private MultiStudentClassroomLinkMapper classStudentMapper;

	private MultiTeacherClassroomLinkMapper classTeacherMapper;


	/**
	 * 移动端注册用户
	 *
	 * @param phone
	 * @param pwd
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/27 10:54
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public R register(String phone, String pwd, String showname) {

		//校验手机号用户名是否存在
		QueryWrapper<Member> query = new QueryWrapper<Member>();
		query.eq("username", phone).eq("del_flag", CommonConstants.STATUS_NORMAL);
		Member member = baseMapper.selectOne(query);

		//手机号已注册
		if (member != null) {
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage());
		} else {
			//注册会员
			regiseter(phone, pwd, null, null, showname);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}

	/**
	 * 移动端注册用户
	 *
	 * @param phone
	 * @param pwd
	 * @param type   1-微信注册 2-IOS注册 3-上音社引流注册
	 * @param openId
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/27 10:53
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public R register(String phone, String pwd, String type, String openId, String showname) {

		//校验手机号用户名是否存在
		QueryWrapper<Member> query = new QueryWrapper<Member>();
		query.eq("username", phone).eq("del_flag", CommonConstants.STATUS_NORMAL);
		Member member = baseMapper.selectOne(query);

		//手机号已注册
		if (member != null) {
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage());
		} else {
			//注册会员
			regiseter(phone, pwd, type, openId, showname);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}

	/**
	 * 分页查询会员信息
	 *
	 * @param page
	 * @param memberV2DTO
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.member.api.vo.MemberV2VO>
	 * @author nianhua.jiang
	 * @date 2020/5/22 10:05
	 */
	@Override
	public IPage<MemberV2VO> getMemberVosPageV2(Page page, MemberV2DTO memberV2DTO) {
		return memberMapper.getMemberVosPageV2(page, memberV2DTO);
	}

	/**
	 * 新增会员(后台管理新增)
	 *
	 * @param memberDTO
	 * @return boolean
	 * @author nianhua.jiang
	 * @date 2020/5/25 11:49
	 */
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public R addMember(MemberV2DTO memberDTO) {

		// 校验手机号
		QueryWrapper<Member> queryPhone = new QueryWrapper<>();
		queryPhone.eq("username", memberDTO.getPhone()).eq("del_flag", Constant.DEL_FLAG);
		Member memberPhone = baseMapper.selectOne(queryPhone);
		if (memberPhone != null) {
			//手机号重复
			return new R(CommonConstants.FAIL, "手机号重复", false);
		}

		Member member = new Member();

		// 保存用户
		member.setUsername(memberDTO.getPhone());
		//昵称
		member.setShowname(memberDTO.getShowname());
		//账户唯一ID
		member.setAccount(getAccount());
		//设置默认密码
		member.setPassword(ENCODER.encode("123456"));
		//电话号码
		member.setPhone(memberDTO.getPhone());
		//创建时间
		member.setCreateTime(LocalDateTime.now());
		//逻辑删除
		member.setDelFlag(Constant.DEL_FLAG);
		//用户身份
		member.setIsTeacher(
				StringUtils.isEmpty(memberDTO.getIdentity()) ? "0" : memberDTO.getIdentity());

		//是否有注册送打印次数的活动
		List<ErpActivityInfo> erpActivityInfos = activityInfoMapper
				.selectList(new QueryWrapper<ErpActivityInfo>()
						//注册送打印次数
						.eq(ErpActivityInfo.COL_TYPE, "1")
						//状态为激活
						.and(x -> x.eq(ErpActivityInfo.COL_IS_ENABLED, "1")));

		//打印次数
		int printCount = 0;

		for (ErpActivityInfo erpActivityInfo : erpActivityInfos) {
			printCount += erpActivityInfo.getFreeAmount();
		}
		member.setPrintAmountGive(printCount);

		if (memberDTO.getOptId() == null) {
			member.setOptId(999999);
		} else {
			member.setOptId(memberDTO.getOptId());
		}

		baseMapper.insert(member);

		// 根据手机号查询用户
		Member memberAfter = baseMapper.selectOne(queryPhone);

		//如果为教师身份，则创建工作室
		if ("1".equals(memberDTO.getIdentity())) {

			//工作室名称为空，返回错误信息
			if (memberDTO.getStudioName().isEmpty()) {
				return new R(CommonConstants.FAIL, "工作室名称参数错误", false);
			}

			//在判断工作室名称是否重复
			else {

				List<OrganizationCommon> orgList = organizationCommonMapper.selectList(
						new QueryWrapper<OrganizationCommon>()
								.eq("name", memberDTO.getStudioName()));
				if (orgList.size() > 0) {
					throw new BusinessException("工作室名称重复");
				}

				//新建工作室
				else {
					OrganizationCommon office = new OrganizationCommon();
					office.setProvince(memberDTO.getProvince());
					office.setCity(memberDTO.getCity());
					//创建时间
					office.setCreateTime(new Date());
					//创建者
					office.setCreateUser(memberAfter.getId());
					//在线陪练 -> 开通
					office.setAccompany("1");
					//状态 -> 启用
					office.setStatus("0");
					//工作室
					office.setIsStudio("1");
					//电话号码
					office.setPhone(memberAfter.getPhone());
					//工作室名称
					office.setName(memberDTO.getStudioName());
					//密码：用户密码
					office.setPsw(memberAfter.getPassword());
					//机构码
					office.setCode(getCode());
					//新增
					organizationCommonMapper.insert(office);

					//新增教师详情
					OrgTeacherDetailed orgTeacherDetailed = new OrgTeacherDetailed();
					//用户ID
					orgTeacherDetailed.setMemberId(memberAfter.getId());
					//创建时间
					orgTeacherDetailed.setCreateTime(new Date());
					//教师姓名
					orgTeacherDetailed.setName(memberAfter.getShowname());
					//教师机构ID
					orgTeacherDetailed.setOrgId(office.getId());

					teacherDetailedMapper.insert(orgTeacherDetailed);

					//新增教师认证表
					SmMemberTeacherApprovalNew teacherApproval = new SmMemberTeacherApprovalNewVO();
					//状态：已通过
					teacherApproval.setStatus("1");
					//电话号码
					teacherApproval.setPhone(member.getPhone());
					//用户ID
					teacherApproval.setMemberId(member.getId());
					//教师姓名
					teacherApproval.setName(memberDTO.getShowname());
					//省编号
					teacherApproval.setProvinceCode(memberDTO.getProvinceCode());
					//省名称
					teacherApproval.setProvinceName(memberDTO.getProvince());
					//市编号
					teacherApproval.setCityCode(memberDTO.getCityCode());
					//市名称
					teacherApproval.setCityName(memberDTO.getCity());
					//工作室名称
					teacherApproval.setStudioName(memberDTO.getStudioName());
					//创建时间
					teacherApproval.setCreateTime(new Date());

					teacherApprovalMapper.insert(teacherApproval);

					//更新后台角色
					SysUser sysUser = new SysUser();
					//用户名
					sysUser.setUsername(member.getPhone());
					//密码
					sysUser.setPassword(ENCODER.encode("123456"));
					//手机号码
					sysUser.setPhone(member.getPhone());
					//头像
					sysUser.setAvatar(member.getAvatar());
					//部门ID 固定写死 为 25
					sysUser.setDeptId(25);
					//是否锁定
					sysUser.setLockFlag("0");
					//逻辑删除
					sysUser.setDelFlag("0");
					//创建时间
					sysUser.setCreateTime(new Date());
					//新增后台管理的用户信息
					int result = sysUserMapper.insertSysUser(sysUser);

					//插入用户-角色关系表
					SysUserRole sysUserRole = new SysUserRole();
					//userId
					sysUserRole.setUserId(sysUser.getUserId());
					//角色ID - 固定为机构角色
					sysUserRole.setRoleId(19);
					//新增用户角色关系表
					sysUserRoleMapper.insertRole(sysUserRole);

					//插入运营商机构关系表
					OptOrg optOrg = new OptOrg();
					optOrg.setOptId(memberDTO.getOptId());
					optOrg.setOrgId(office.getId());
					optOrgMapper.insert(optOrg);

				}
			}
		}

		//新建会员详情
		MemberDetailInfo info = new MemberDetailInfo();
		//member id
		info.setMemberId(memberAfter.getId());
		//生日
		info.setBirthday(memberDTO.getBirthday());
		//性别
		info.setSex(memberDTO.getSex());
		//创建时间
		info.setCreateTime(LocalDateTime.now());
		memberDetailInfoMapper.insert(info);

		return new R(CommonConstants.SUCCESS, "新建成功", true);
	}

	/**
	 * 更新会员信息
	 *
	 * @param memberDTO
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/25 15:34
	 */
	@Override
	public R<Boolean> updateMember(MemberV2DTO memberDTO) {

		//主键查询member信息
		Member member = memberMapper.selectById(memberDTO.getId());

		//如果是老师则可以更改工作室信息
		if (member.getIsTeacher().equals("1")) {
			QueryWrapper queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("phone", member.getPhone());
			OrganizationCommon newOffice = organizationCommonMapper.selectOne(queryWrapper);
			newOffice.setProvince(memberDTO.getProvince());
			newOffice.setCity(memberDTO.getCity());
			organizationCommonMapper.updateById(newOffice);
		}

		//手机号改动的情况下需要判断手机号是否重复
		if (!member.getPhone().equals(memberDTO.getPhone())) {

			List<Member> phone = memberMapper
					.selectList(new QueryWrapper<Member>().eq("phone", memberDTO.getPhone()));

			if (phone.size() > 0) {
				return new R(CommonConstants.FAIL, "手机号已存在", false);
			}

		}

		// 用户身份发生修改
		if (!member.getIsTeacher().equals(memberDTO.getIdentity())) {

			//当用户身份由【学生】修改为【教师】时，需要新增工作室
			if (IDENTITY_TEACHER.equals(memberDTO.getIdentity())) {

				OrganizationCommon office = new OrganizationCommon();
				//创建时间
				office.setCreateTime(new Date());
				//创建者
				office.setCreateUser(member.getId());
				//在线陪练 -> 开通
				office.setAccompany("1");
				//工作室
				office.setIsStudio("1");
				//状态 -> 启用
				office.setStatus("0");
				//电话号码
				office.setPhone(memberDTO.getPhone());
				//工作室名称
				office.setName(memberDTO.getStudioName());
				//密码：用户密码
				office.setPsw(member.getPassword());
				//机构码
				office.setCode(getCode());

				office.setProvince(memberDTO.getProvince());
				office.setCity(memberDTO.getCity());

				//新增
				int insert = organizationCommonMapper.insert(office);

				if (insert == 1) {
					//member表的用户身份改为【教师】
					member.setIsTeacher(IDENTITY_TEACHER);
				}

				//新增教师信息
				OrgTeacherDetailed teacherDetailed = new OrgTeacherDetailed();
				//用户ID
				teacherDetailed.setMemberId(member.getId());
				//机构ID
				teacherDetailed.setOrgId(office.getId());
				//逻辑删除
				teacherDetailed.setDelFlag("0");
				//教师姓名
				teacherDetailed.setName(member.getShowname());
				//创建时间
				teacherDetailed.setCreateTime(new Date());
				//创建人
				teacherDetailed.setCreateUser(member.getId());

				//新增教师详情
				teacherDetailedMapper.insert(teacherDetailed);

				//新增教师认证表
				SmMemberTeacherApprovalNew teacherApproval = new SmMemberTeacherApprovalNewVO();
				//状态：已通过
				teacherApproval.setStatus("1");
				//电话号码
				teacherApproval.setPhone(member.getPhone());
				//用户ID
				teacherApproval.setMemberId(member.getId());
				//教师姓名
				teacherApproval.setName(memberDTO.getShowname());
				//省编号
				teacherApproval.setProvinceCode(memberDTO.getProvinceCode());
				//省名称
				teacherApproval.setProvinceName(memberDTO.getProvinceName());
				//市编号
				teacherApproval.setCityCode(memberDTO.getCityCode());
				//市名称
				teacherApproval.setCityName(memberDTO.getCityName());

				teacherApprovalMapper.insert(teacherApproval);

				//更新后台角色
				SysUser sysUser = new SysUser();
				//用户名
				sysUser.setUsername(member.getPhone());
				//密码
				sysUser.setPassword(ENCODER.encode("123456"));
				//手机号码
				sysUser.setPhone(member.getPhone());
				//头像
				sysUser.setAvatar(member.getAvatar());
				//部门ID 固定写死 为 25
				sysUser.setDeptId(25);
				//是否锁定
				sysUser.setLockFlag("0");
				//逻辑删除
				sysUser.setDelFlag("0");
				//创建时间
				sysUser.setCreateTime(new Date());
				//新增后台管理的用户信息
				int result = sysUserMapper.insertSysUser(sysUser);

				//插入用户-角色关系表
				SysUserRole sysUserRole = new SysUserRole();
				//userId
				sysUserRole.setUserId(sysUser.getUserId());
				//角色ID - 固定为机构角色
				sysUserRole.setRoleId(19);
				//新增用户角色关系表
				sysUserRoleMapper.insertRole(sysUserRole);

			}
		}

		//电话号
		member.setPhone(memberDTO.getPhone());
		//昵称
		member.setShowname(memberDTO.getShowname());

		//状态
		member.setLockFlag(memberDTO.getLockFlag());

		//更新会员表
		memberMapper.updateById(member);

		//更新会员详情表
		MemberDetailInfo info = memberDetailInfoMapper
				.selectOne(new QueryWrapper<MemberDetailInfo>().eq("member_id", member.getId()));

		//若会员详情表为空，则执行插入操作
		if (info == null) {
			MemberDetailInfo insertInfo = new MemberDetailInfo();
			//生日
			insertInfo.setBirthday(memberDTO.getBirthday());
			//性别
			insertInfo.setSex(memberDTO.getSex());
			//member_id
			insertInfo.setMemberId(member.getId());
			//创建时间
			insertInfo.setCreateTime(LocalDateTime.now());
			//更新时间
			insertInfo.setUpdateTime(LocalDateTime.now());
			memberDetailInfoMapper.insert(insertInfo);
		}
		//否则执行更新操作
		else {
			//生日
			info.setBirthday(memberDTO.getBirthday());
			//性别
			info.setSex(memberDTO.getSex());
			//更新
			memberDetailInfoMapper.updateById(info);
		}

		//如果将此用户锁定
		if ("9".equals(memberDTO.getLockFlag())) {

			//将学生信息删除
			memberMapper.delStudent(member.getId());
			//如果是教师，将教师删除
			if (IDENTITY_TEACHER.equals(member.getIsTeacher())) {
				memberMapper.delTeacher(member.getId());
			}

		}

		return new R<>(CommonConstants.SUCCESS, "修改成功", true);

	}

	/**
	 * 获取所属关系
	 *
	 * @param id
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/5/26 9:52
	 */
	@Override
	public List<RelationshipVO> getRelationship(String id) {
		return memberMapper.getRelationship(id);
	}

	/**
	 * 获取用户详情
	 *
	 * @param id
	 * @return com.shycloud.mido.member.api.vo.MemberDetailVO
	 * @author nianhua.jiang
	 * @date 2020/5/26 16:07
	 */
	@Override
	public MemberDetailVO getMemberDetail(String id) {

		MemberDetailVO memberDetailVO = new MemberDetailVO();

		//获取用户信息
		Member member = memberMapper.selectById(id);
		//手机号
		memberDetailVO.setPhone(member.getPhone());
		//昵称
		memberDetailVO.setShowname(member.getShowname());
		//用户身份
		memberDetailVO.setIdentity(member.getIsTeacher());
		//状态
		memberDetailVO.setLockFlag(member.getLockFlag());
		//头像
		memberDetailVO.setAvatar(member.getAvatar());

		//获取工作室信息
		if (member.getIsTeacher().equals("1")) {
			String orgName = memberDetailInfoMapper.selectOrg(member.getPhone());
			OrgDto orgDto = memberDetailInfoMapper.selectOrgInfo(member.getPhone());
			memberDetailVO.setStudioName(orgName);
			memberDetailVO.setProvince(orgDto.getProvince());
			memberDetailVO.setCity(orgDto.getCity());
		}
		//获取会员详情
		MemberDetailInfo memberInfo = memberDetailInfoMapper
				.selectOne(new QueryWrapper<MemberDetailInfo>().eq("member_id", id));
		if (memberInfo != null) {
			//生日
			memberDetailVO.setBirthday(memberInfo.getBirthday());
			//性别
			memberDetailVO.setSex(memberInfo.getSex());
		}
		//获取硬件信息
		R result = masterFeignService.checkMemberMaster(id);
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		memberDetailVO.setIsMaster((Integer) resultMap.get("status") == 1 ? "1" : "0");
		//获取会员信息
		//是否是会员
		VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(id);
		memberDetailVO.setIsVip(vipMemberVO.getIsVipString());
		return memberDetailVO;
	}

	/**
	 * 移除所属关系
	 *
	 * @param studentId
	 * @param teacherId
	 * @return boolean
	 * @author nianhua.jiang
	 * @date 2020/5/26 11:22
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public int removeRelationship(String studentId, String teacherId) {

		//移除成功
		if (memberMapper.removeRelationship(studentId, teacherId) == 1) {
			//更新学生表的【逻辑删除】
			return memberMapper.delOrgStu(studentId);
		}
		return 0;
	}

	/**
	 * 分页获取用户vip信息
	 *
	 * @param page
	 * @param phone
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.member.api.vo.MemberV2VO>
	 * @author nianhua.jiang
	 * @date 2020/5/29 13:32
	 */
	@Override
	public IPage<MemberV2VO> getVipMember(Page page, String phone, String identity, Integer dayLeft,
			String startDate, String endDate) {
		return memberMapper.getVipMember(page, phone, identity, dayLeft, startDate, endDate);
	}

	/**
	 * 开通会员
	 *
	 * @param phone
	 * @param useTime
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/6/2 17:28
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean addVipMember(String phone, Integer useTime) {

		//根据手机号查询member信息
		Member member = memberMapper.selectOne(new QueryWrapper<Member>().eq("username", phone));

		MemberRole role = memberRoleMapper.selectOne(Wrappers
				.<MemberRole>query().lambda()
				.eq(MemberRole::getMemberId, member.getId())
				.eq(MemberRole::getRoleCode, Constant.VIP_MEMBER));

		//如果此用户开过会员
		if (role != null) {

			LocalDateTime endTime = role.getEndTime();
			//若到期时间在今日之后，则正常延期
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				//延长期限
				role.setEndTime(endTime.plusDays(useTime));
			}

			//若到期时间在今天之前，那么需要更新开始日期以及结束日期
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusDays(useTime));
			}
			memberRoleMapper.updMemberRole(role);
		}

		//若此用户没有开过会员
		else {
			MemberRole role2 = new MemberRole();
			role2.setCreateTime(LocalDateTime.now());
			role2.setStartTime(LocalDateTime.now());
			//开通会员天数
			role2.setEndTime(LocalDateTime.now().plusDays(useTime));
			role2.setRoleCode(Constant.VIP_MEMBER);
			role2.setMemberId(member.getId());
			role2.setDelFlag(Constant.DEL_FLAG);
			memberRoleMapper.saveMemberRole(role2);
		}
		return true;
	}


	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean assignVip(String memberId, Integer number) {

		int duration = number * 365;

		//根据手机号查询member信息
		Member member = memberMapper.selectById(memberId);

		//记录操作人
		if (SecurityUtils.getUser() != null) {

			// 记录会员延期操作日志
			String username = SecurityUtils.getUser().getUsername();
			SysActLogZebra sysActLogZebra = new SysActLogZebra();
			//创建时间
			sysActLogZebra.setCreateTime(LocalDateTime.now());
			//操作人信息
			sysActLogZebra.setCreateUser(username);
			//目标用户ID
			sysActLogZebra.setMemberId(memberId);
			//类型
			sysActLogZebra.setType("2");
			// 时长
			sysActLogZebra.setDuration(duration);
			adminFeignService.saveZebraLog(sysActLogZebra);

			// 记录主账号分配会员操作日志
			SysActLogZebra sysMemberActLogZebra = new SysActLogZebra();
			//创建时间
			sysMemberActLogZebra.setCreateTime(LocalDateTime.now());
			//操作人信息
			sysMemberActLogZebra.setCreateUser(username);
			//目标用户ID
			sysMemberActLogZebra.setMemberId(memberId);
			//类型
			sysMemberActLogZebra.setType("3");
			// 1等于1年
			sysMemberActLogZebra.setDuration(number);
			adminFeignService.saveZebraLog(sysActLogZebra);
		}

		MemberRole role = memberRoleMapper.selectOne(Wrappers
				.<MemberRole>query().lambda()
				.eq(MemberRole::getMemberId, member.getId())
				.eq(MemberRole::getRoleCode, Constant.VIP_MEMBER));

		//如果此用户开过会员
		if (role != null) {

			LocalDateTime endTime = role.getEndTime();
			//若到期时间在今日之后，则正常延期
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				//延长期限
				role.setEndTime(endTime.plusDays(duration));
			}

			//若到期时间在今天之前，那么需要更新开始日期以及结束日期
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusDays(duration));
			}
			memberRoleMapper.updMemberRole(role);
		}

		//若此用户没有开过会员
		else {
			MemberRole role2 = new MemberRole();
			role2.setCreateTime(LocalDateTime.now());
			role2.setStartTime(LocalDateTime.now());
			//开通会员天数
			role2.setEndTime(LocalDateTime.now().plusDays(duration));
			role2.setRoleCode(Constant.VIP_MEMBER);
			role2.setMemberId(member.getId());
			role2.setDelFlag(Constant.DEL_FLAG);
			memberRoleMapper.saveMemberRole(role2);
		}

		// 减少赠送会员次数
		member.setGiftMembership( member.getGiftMembership() - number);
		memberMapper.updateById( member);

		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean addVipMemberByMemberId(String memberId, Integer duration) {

		//根据手机号查询member信息
		Member member = memberMapper.selectById(memberId);

		//记录操作人
		if (SecurityUtils.getUser() != null) {
			String username = SecurityUtils.getUser().getUsername();
			SysActLogZebra sysActLogZebra = new SysActLogZebra();
			//创建时间
			sysActLogZebra.setCreateTime(LocalDateTime.now());
			//操作人信息
			sysActLogZebra.setCreateUser(username);
			//目标用户ID
			sysActLogZebra.setMemberId(memberId);
			//类型
			sysActLogZebra.setType("2");
			//时长
			sysActLogZebra.setDuration(duration);
			adminFeignService.saveZebraLog(sysActLogZebra);
		}

		MemberRole role = memberRoleMapper.selectOne(Wrappers
				.<MemberRole>query().lambda()
				.eq(MemberRole::getMemberId, member.getId())
				.eq(MemberRole::getRoleCode, Constant.VIP_MEMBER));

		//如果此用户开过会员
		if (role != null) {

			LocalDateTime endTime = role.getEndTime();
			//若到期时间在今日之后，则正常延期
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				//延长期限
				role.setEndTime(endTime.plusDays(duration));
			}

			//若到期时间在今天之前，那么需要更新开始日期以及结束日期
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusDays(duration));
			}
			memberRoleMapper.updMemberRole(role);
		}

		//若此用户没有开过会员
		else {
			MemberRole role2 = new MemberRole();
			role2.setCreateTime(LocalDateTime.now());
			role2.setStartTime(LocalDateTime.now());
			//开通会员天数
			role2.setEndTime(LocalDateTime.now().plusDays(duration));
			role2.setRoleCode(Constant.VIP_MEMBER);
			role2.setMemberId(member.getId());
			role2.setDelFlag(Constant.DEL_FLAG);
			memberRoleMapper.saveMemberRole(role2);
		}
		return true;
	}

	/**
	 * 根据手机号获取会员信息
	 *
	 * @param phone
	 * @return com.shycloud.mido.music.vo.MemberVO
	 * @author nianhua.jiang
	 * @date 2020/5/27 13:46
	 */
	@Override
	public MemberVO getMemberByPhone(String phone) {

		//查询此用户是否激活过会员体验
		Integer isActive = memberMapper.searchActive(phone);

		MemberVO member = memberMapper.getMemberByPhone(phone);
		if (member != null) {
			member.setIsActive(isActive.toString());
		}
		return member;
	}

	/**
	 * 根据用户账号查询用户所在机构
	 *
	 * @param username
	 * @return java.util.List<java.util.Map < java.lang.String, java.lang.String>>
	 * @author nianhua.jiang
	 * @date 2020/6/8 14:40
	 */
	@Override
	public List<Map<String, String>> getOrgListByUsername(String username) {

		QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
		//用户名
		queryWrapper.eq("username", username);
		//逻辑删除
		queryWrapper.eq("del_flag", "0");
		//是否锁定 - 未锁定
		queryWrapper.eq("lock_flag", "0");
		//查询member信息
		Member member = memberMapper.selectOne(queryWrapper);

		List<Map<String, String>> resultMap = new ArrayList<>();

		//如果此用户为教师身份，查询teacher表，检索出机构信息
		if (IDENTITY_TEACHER.equals(member.getIsTeacher())) {
			resultMap = memberMapper.getOrgTeacher(member.getId());
		}

		//如果此用户为学生身份，查询student表，检索出机构信息
		if (IDENTITY_STUDENT.equals(member.getIsTeacher())) {
			resultMap = memberMapper.getOrgStudent(member.getId());
		}
		return resultMap;
	}

	/**
	 * 登录时获取会员信息
	 *
	 * @param username
	 * @return com.shycloud.mido.member.api.vo.MemberDetailForLoginVO
	 * @author nianhua.jiang
	 * @date 2020/6/23 14:25
	 */
	@Override
	public MemberDetailForLoginVO getUserDetail(String username) {
		return memberMapper.getUserDetail(username);
	}

	/**
	 * 登录时获取会员信息
	 *
	 * @param phone
	 * @return com.shycloud.mido.member.api.vo.MemberDetailForLoginVO
	 * @author nianhua.jiang
	 * @date 2020/6/23 14:25
	 */
	@Override
	public MemberDetailForLoginVO getUserDetailByPhone(String phone) {
		return memberMapper.getUserDetailByPhone(phone);
	}

	/**
	 * 移动端更新会员信息
	 *
	 * @param map
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/6/28 14:38
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean updateMobileUser(Map<String, String> map) {

		//头像
		String header = map.get("header");
		//昵称
		String showName = map.get("showName");
		//密码
		//String pwd = ENCODER.encode(map.get("pwd"));

		//member_id
		String memberId = SecurityUtils.getMember().getId();

		//琴龄（1年以下 = 0 | 1~2年 = 1）
		String playYears = map.get("playYears");
		//目标
		String playTarget = map.get("playTarget");

		//根据ID查询会员表
		Member member = memberMapper.selectById(memberId);
		//昵称
		member.setShowname(showName);
		//头像
		member.setAvatar(header);
		//密码
		//member.setPassword(pwd);
		//更新时间
		member.setUpdateTime(LocalDateTime.now());
		//更新会员表
		int result = memberMapper.updateById(member);

		//出生日期
		String birthday = map.get("birthday");
		//性别
		String sex = map.get("sex");

		//更新会员详情表，先查询数据，如果无会员详情信息，则新建
		MemberDetailInfo memberDetailInfo = memberDetailInfoMapper
				.selectOne(new QueryWrapper<MemberDetailInfo>().eq("member_id", memberId));
		int result2 = 0;
		//更新操作
		if (memberDetailInfo != null) {
			//更新日期
			memberDetailInfo.setUpdateTime(LocalDateTime.now());
			//出生日期
			memberDetailInfo.setBirthday(birthday);
			//性别
			memberDetailInfo.setSex(sex);
			//琴龄
			memberDetailInfo.setPlayYears(playYears);
			//目标
			memberDetailInfo.setPlayTarget(playTarget);
			//更新
			result2 = memberDetailInfoMapper.updateById(memberDetailInfo);
		}
		//插入操作
		else {
			MemberDetailInfo memberDetailInfoNew = new MemberDetailInfo();
			//memberId
			memberDetailInfoNew.setMemberId(memberId);
			//生日
			memberDetailInfoNew.setBirthday(birthday);
			//性别（0：男 1 女）
			memberDetailInfoNew.setSex(sex);
			//创建时间
			memberDetailInfoNew.setCreateTime(LocalDateTime.now());
			//更新时间
			memberDetailInfoNew.setUpdateTime(LocalDateTime.now());
			//琴龄
			memberDetailInfoNew.setPlayYears(playYears);
			//目标
			memberDetailInfoNew.setPlayTarget(playTarget);
			//新增操作
			result2 = memberDetailInfoMapper.insert(memberDetailInfoNew);
		}

		if (result == 1 && result2 == 1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取提醒信息
	 *
	 * @param studentId
	 * @return java.util.List<java.lang.String>
	 * @author nianhua.jiang
	 * @date 2020/7/6 13:22
	 */
	@Override
	public List<String> getDing(String studentId) {
		return memberMapper.getDing(studentId);
	}

	@Override
	public R updClientId(String memberId, String clientId) {
		return new R<>(memberMapper.updClientId(memberId, clientId),
				com.shycloud.mido.member.api.enums.MessageCodeEnum.SUCCESS.getMessage());
	}

	/**
	 * 扫码添加学生
	 *
	 * @param map
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/8/17 13:22
	 */
	@Override
	public OrgTeacherStudent addStudent(Map<String, Object> map) {

		Integer orgId = null;

		//机构ID
		if (map.get(PARAM_ORG_ID) != null) {
			orgId = (Integer) map.get(PARAM_ORG_ID);
		}
		//教师端的member_id
		String teacherMemberId = (String) map.get(PARAM_TEACHER_MEMBER_ID);
		//学生端的member_id
		String studentMemberId = (String) map.get(PARAM_STUDENT_MEMBER_ID);
		//扫码人的身份 teacher = 1  student = 0
		String identity = (String) map.get(PARAM_IDENTITY);

		//教师端 member 详情
		Member memberT = memberMapper.selectById(teacherMemberId);
		//学生端 member 详情
		Member memberS = memberMapper.selectById(studentMemberId);

		if (memberT.getIsTeacher().equals(memberS.getIsTeacher())) {
			throw new BusinessException("相同身份无法添加师生关系");
		}

		//获取教师Id
		String teacherId = teacherService.getTeacher(orgId, teacherMemberId).getId();

		if (teacherId == null) {
			throw new BusinessException("教师信息获取失败，请确认教师的身份");
		}

		//判断此学生是否跟其他机构绑定
		OrgStudentDetailed studentDetailed = studentMapper
				.selectOne(new QueryWrapper<OrgStudentDetailed>()
						.eq(OrgStudentDetailed.COL_MEMBER_ID, studentMemberId)
						.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG,
								CommonConstants.STATUS_NORMAL)));

		if (studentDetailed != null) {

			if (studentDetailed.getOrgId().equals(orgId)) {

				//再判断此学生是否跟此教师绑定
				OrgTeacherStudent orgTeacherStudent = teacherStudentMapper
						.selectOne(new QueryWrapper<OrgTeacherStudent>()
								.eq(OrgTeacherStudent.COL_TEACHER_ID, teacherId)
								.and(x -> x.eq(OrgTeacherStudent.COL_STUDENT_ID,
										studentDetailed.getId())));

				if (orgTeacherStudent != null && IDENTITY_TEACHER.equals(identity)) {
					throw new BusinessException("此学生与您已经相互绑定，无需重复绑定");
				} else if (orgTeacherStudent != null && IDENTITY_STUDENT.equals(identity)) {
					throw new BusinessException("您已经与此教师绑定，无需重复绑定");
				} else if (orgTeacherStudent == null && IDENTITY_TEACHER.equals(identity)) {
					throw new BusinessException(2, "此学生已与机构内其他教师绑定");
				} else if (orgTeacherStudent == null && IDENTITY_STUDENT.equals(identity)) {
					throw new BusinessException(2, "您已与机构内其他教师绑定");
				}

			} else {
				//学生未绑定教师
				if (studentDetailed.getOrgId() == 0) {
					teacherService.addStudentByTeacher(orgId, teacherId, studentMemberId,
							studentDetailed);
					memberS.setOrgId(orgId);

					//查询此机构对应的运营商，默认归属总部
					List<OptOrg> optOrgs = optOrgMapper
							.selectList(new QueryWrapper<OptOrg>().eq(OptOrg.COL_ORG_ID, orgId));

					if (optOrgs.size() == 0) {
						memberS.setOptId(999999);
					} else {
						memberS.setOptId(optOrgs.get(0).getOptId());
					}

					memberMapper.updateById(memberS);
				} else {
					//扫码的人为【教师】身份
					if (IDENTITY_TEACHER.equals(identity)) {
						throw new BusinessException(2, "此学生已经被其他机构绑定");
					} else {
						throw new BusinessException(2, "您已经被其他机构绑定");
					}
				}
			}
		}

		OrgTeacherStudent orgTeacherStudent = new OrgTeacherStudent();

		orgTeacherStudent.setTeacherId(teacherId);

		orgTeacherStudent.setOrgId(orgId);
		// 2021-06-10 推送师生绑定成功消息
		//扫码的人为【教师】身份,需要给学生推送
		if (IDENTITY_TEACHER.equals(identity)) {
			//------------------ 给学生推送 --------------------//
			if (memberS.getClientId() != null) {
				JPushUtils.sendJPush("新老师", "您有老师了", memberS.getClientId());
				//通知APP请求接口
				JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_APP_HOMEPAGE_VIEW.getType(),
						memberS.getClientId(), "请求 getMsgApp 接口");
			}
			//String msgIdS = addMsg("新老师", "您有老师了", memberS.getClientId(), "", "", "2");
			String msgIdS = "new_teacher_to_student";
			msgMemberInfoService.sendMsg(msgIdS, "sys", memberS.getId());
			//------------------------------------------------//
		} else {
			//------------------ 给教师推送 --------------------//
			if (memberT.getClientId() != null) {
				JPushUtils.sendJPush("新学生", "您有新学生了", memberT.getClientId());
				//通知APP请求接口
				JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_APP_HOMEPAGE_VIEW.getType(),
						memberT.getClientId(), "请求 getMsgApp 接口");
			}
			//String msgIdT = addMsg("新学生", "您有新学生了", memberT.getClientId(), "", "", "1");
			String msgIdT = "new_student_to_teacher";
			msgMemberInfoService.sendMsg(msgIdT, "sys", memberT.getId());
			//------------------------------------------------//
		}
		return orgTeacherStudent;
	}

	@Override
	public OrgTeacherStudent addStudentByUsername(Map<String, Object> map) {

		//机构ID
		Integer orgId = (Integer) map.get(PARAM_ORG_ID);
		//教师的账号
		String teacherUsername = (String) map.get(PARAM_TEACHER_USERNAME);
		//学生的账号
		String studentUsername = (String) map.get(PARAM_STUDENT_USERNAME);
		//添加人的身份 teacher = 1  student = 0
		String identity = (String) map.get(PARAM_IDENTITY);

		//加入同步锁
		//RLock lock = redissonClient.getLock("addStudentByUsername:" + teacherUsername + "_" + studentUsername);

		//lock.lock(5, TimeUnit.SECONDS);

		List<Member> studentMembers = memberMapper
				.selectList(new QueryWrapper<Member>().eq("username", studentUsername));

		if (studentMembers.size() == 0) {
			//lock.unlock();
			throw new BusinessException("学生账号不存在");
		}

		List<Member> teacherMembers = memberMapper
				.selectList(new QueryWrapper<Member>().eq("username", teacherUsername));

		if (teacherMembers.size() == 0) {
			//lock.unlock();
			throw new BusinessException("教师账号不存在");
		}

		if (orgId == null) {
			//获取教师的机构ID
			List<OrgTeacherDetailed> teacherDetaileds = teacherDetailedMapper.selectList(
					new QueryWrapper<OrgTeacherDetailed>()
							.eq("member_id", teacherMembers.get(0).getId()));
			if (teacherDetaileds.size() == 0) {
				//lock.unlock();
				throw new BusinessException("教师信息获取失败，请确认教师账号是否正确");
			}
			map.put(PARAM_ORG_ID, teacherDetaileds.get(0).getOrgId());
		}

		map.put(PARAM_TEACHER_MEMBER_ID, teacherMembers.get(0).getId());

		map.put(PARAM_STUDENT_MEMBER_ID, studentMembers.get(0).getId());
		//lock.unlock();
		return addStudent(map);
	}

	@Override
	public Boolean addPlayTimeDaily(String studentId, int timeSpent, String dateString,
			String memberId) throws ParseException {
		StudentPlayTimeDaily existing = studentPlayTimeDailyMapper.selectOne(
				new QueryWrapper<StudentPlayTimeDaily>().eq("date",
						dateString != null ? dateString :
								new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
						.eq("member_id", memberId));

		StudentPlayTimeDaily playTime = new StudentPlayTimeDaily();

		if (existing == null) {
			playTime.setStudentId(studentId);
			playTime.setDate(
					dateString != null ?
							new SimpleDateFormat("yyyy-MM-dd").parse(dateString)
							: new Date());
			playTime.setCreateTime(LocalDateTime.now());
			playTime.setUpdateTime(LocalDateTime.now());
			playTime.setMemberId(memberId);

			playTime.setPlayTime(timeSpent);
			return studentPlayTimeDailyMapper.insert(playTime) == 1 ? true : false;
		} else {
			int sum = existing.getPlayTime() + timeSpent;
			//一天不能超过86400秒，防止恶意刷时长
			existing.setPlayTime(sum >= 86400 ? 86400 : sum);
			existing.setUpdateTime(LocalDateTime.now());
			return studentPlayTimeDailyMapper.updateById(existing) == 1 ? true : false;
		}
	}

	@Override
	public StudentPlayTimeDaily getPlayTimeDaily(String memberId, String dateString) {
		return studentPlayTimeDailyMapper.selectOne(new QueryWrapper<StudentPlayTimeDaily>()
				.eq("member_id", memberId).and(x -> x.eq("date", dateString)));
	}

	@Override
	public List<SmMemberPlayRewardInfo> getRewardInfo() {
		return smMemberPlayRewardInfoMapper.selectList(
				new QueryWrapper<SmMemberPlayRewardInfo>());
	}

	@Override
	public Map updateMemberExp(Integer rewardId, String memberId) {
		Map returnMap = new HashMap();
		Member member = getById(memberId);

		//验重逻辑
		String concatKey = checkIfClaimedAlready(returnMap, memberId, rewardId, member, "exp");
		if ((boolean) returnMap.get("result") == false) {
			return returnMap;
		}

		SmMemberPlayRewardInfo info = rewardInfoMapper.selectOne(
				new QueryWrapper<SmMemberPlayRewardInfo>().eq("id", rewardId));

		int currentExp = (member.getExp() == null ? 0 : member.getExp()) + info.getRewardExp();
		member.setExp(currentExp);

		//填写member等级Level
		int level = currentExp / 1000;
		member.setLevel(level);

		boolean result = updateById(member);

		if (result) {
			redisTemplate.opsForValue().set(concatKey, false, 86400, TimeUnit.SECONDS);
		}

		returnMap.put("result", result);
		returnMap.put("exp", result ? currentExp : member.getExp() == null ? 0 : member.getExp());
		returnMap.put("delta", result ? info.getRewardExp() : 0);

		return returnMap;
	}

	@Override
	public Map updateMemberPoints(Integer rewardId, String memberId) {
		Map returnMap = new HashMap();
		Member member = getById(memberId);

		//验重逻辑
		String concatKey = checkIfClaimedAlready(returnMap, memberId, rewardId, member, "points");
		if ((boolean) returnMap.get("result") == false) {
			return returnMap;
		}

		SmMemberPlayRewardInfo info = rewardInfoMapper.selectOne(
				new QueryWrapper<SmMemberPlayRewardInfo>().eq("id", rewardId));

		int curPoints = member.getPoints() + info.getRewardPoints();
		member.setPoints(curPoints);

		boolean result = updateById(member);

		if (result) {
			redisTemplate.opsForValue().set(concatKey, false, 86400, TimeUnit.SECONDS);
		}

		returnMap.put("result", result);
		returnMap.put("points", result ? curPoints : member.getExp() == null ? 0 : member.getExp());
		returnMap.put("delta", result ? info.getRewardPoints() : 0);

		return returnMap;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> claimReward(String paramsJson) {
		Map<String, Object> returnMap = new HashMap();
		List readyForClaim = new ArrayList();
		List claimed = new ArrayList();
		String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer rewardId = paramsJSONObject.getInteger("rewardId");
		String memberId = SecurityUtils.getMember().getId();

		this.updateMemberExp(rewardId, memberId);
		this.updateMemberPoints(rewardId, memberId);

		Member member = this.getById(memberId);
		List<SmMemberPlayRewardInfo> rewardInfoList = this.getRewardInfo();

		StudentPlayTimeDaily playTimeDaily = this.getPlayTimeDaily(
				memberId, dateString);
		Integer playTime = playTimeDaily == null ? 0 : playTimeDaily.getPlayTime();

		for (int i = 0; i < rewardInfoList.size(); i++) {
			Integer tempRewardId = rewardInfoList.get(i).getId();
			String concatKey = dateString + memberId + "_" + tempRewardId;

			Object obj = redisTemplate.opsForValue().get(concatKey);
			if (obj != null) {
				claimed.add(tempRewardId);
			} else if (obj == null
					//分钟换算成秒
					&& playTime >= (rewardInfoList.get(i).getDuration() * 60)) {
				readyForClaim.add(tempRewardId);
			}
		}

		returnMap.put("readyForClaim", readyForClaim);
		returnMap.put("claimed", claimed);
		returnMap.put("points", member.getPoints());
		returnMap.put("exp", member.getExp());
		returnMap.put("playTimeToday", playTime);

		return returnMap;
	}

	/**
	 * 注册会员
	 *
	 * @param phone 电话号码(账号)
	 * @param pwd   密码
	 * @param type  null->普通注册 1-微信注册 2-IOS注册 3-上音社合作注册 4-微信小程序注册
	 * @return java.lang.String
	 * @author nianhua.jiang
	 * @date 2020/6/27 11:06
	 */
	private String regiseter(String phone, String pwd, String type, String openId,
			String showname) {

		//注册会员
		Member member = new Member();
		//账号ID
		member.setAccount(getAccount());

		//APP 注册
		if (Member.APP_REGISTER.equals(type)) {
			member.setPhone(phone);
			//用户名（手机号）
			member.setUsername(phone);
			//注册来源-APP
			member.setRegisterFrom(Member.APP_REGISTER);
		}
		//微信注册
		else if (Member.WX_REGISTER.equals(type)) {
			member.setWxOpenid(openId);
			member.setPhone(phone);
			//用户名（手机号）
			member.setUsername(phone);
			//注册来源
			member.setRegisterFrom(Member.WX_REGISTER);
		}
		//IOS注册
		else if (Member.IOS_REGISTER.equals(type)) {
			member.setAppleOpenId(openId);
			member.setPhone(getAccount());
			//用户名（手机号）
			member.setUsername(getAccount());
			//注册来源
			member.setRegisterFrom(Member.IOS_REGISTER);
		}
		//上音社合作注册
		else if (Member.SY_REGISTER.equals(type)) {
			member.setPhone(phone);
			//用户名（手机号）
			member.setUsername(phone);
			//TODO 上音社合作注册(冗余字段) - 涉及业务:后台管理首页数据统计逻辑
			member.setIsOld("3");
			//上音社合作注册
			member.setRegisterFrom(Member.SY_REGISTER);
		}
		//微信小程序注册
		else if (Member.WX_MINI_REGISTER.equals(type)) {
			member.setPhone(phone);
			//用户名（手机号）
			member.setUsername(phone);
			//微信小程序的 openId
			member.setWxMiniOpenId(openId);
		}
		//默认APP注册
		else {
			member.setPhone(phone);
			//用户名（手机号）
			member.setUsername(phone);
			//注册来源-APP
			member.setRegisterFrom(Member.APP_REGISTER);
		}

		if (showname == null) {
			//昵称（宝贝+手机号后四位）
			member.setShowname("宝贝" + phone.substring(phone.length() - 4, phone.length()));
		} else {
			member.setShowname(showname);
		}

		//密码
		member.setPassword(ENCODER.encode(pwd));
		//创建时间
		member.setCreateTime(LocalDateTime.now());
		//逻辑删除
		member.setDelFlag(CommonConstants.STATUS_NORMAL);

		String sex = "0";

		if (openId != null && "1".equals(type)) {
			//获取微信个人信息，进行绑定
			//更新用户 头像/昵称
			String token = redisTemplate.opsForValue().get("wxOpenId_" + openId).toString();

			//根据 token 获取头像，昵称等个人信息
			String url = String.format(SecurityConstants.WX_USER_INFO_URL, token, openId);

			String result = HttpUtil.get(url);
			System.out.println("=========================微信登录响应用户信息:{" + result + "}");

			if (!result.isEmpty()) {
				//微信昵称
				String nickName = JSONUtil.parseObj(result).get("nickname").toString();
				//微信头像
				String header = JSONUtil.parseObj(result).get("headimgurl").toString();
				//性别
				sex = JSONUtil.parseObj(result).get("sex").toString();
				member.setShowname(nickName);
				member.setAvatar(header);
			}
		}

		//是否有注册送打印次数的活动
		List<ErpActivityInfo> erpActivityInfos = activityInfoMapper
				.selectList(new QueryWrapper<ErpActivityInfo>()
						//注册送打印次数
						.eq(ErpActivityInfo.COL_TYPE, "1")
						//状态为激活
						.and(x -> x.eq(ErpActivityInfo.COL_IS_ENABLED, "1")));

		//打印次数
		int printCount = 0;

		for (ErpActivityInfo erpActivityInfo : erpActivityInfos) {
			printCount += erpActivityInfo.getFreeAmount();
		}

		member.setPrintAmountGive(printCount);

		baseMapper.insert(member);

		//新增 member 详情
		MemberDetailInfo memberDetailInfo = new MemberDetailInfo();
		//默认性别：男
		memberDetailInfo.setSex(sex);
		//memberId
		memberDetailInfo.setMemberId(member.getId());
		//默认出生日期：2010-01-01
		memberDetailInfo.setBirthday("2010-01-01");

		memberDetailInfoMapper.insert(memberDetailInfo);

		return member.getId();
	}

	/**
	 * 随机生成 工作室编码
	 *
	 * @param
	 * @return java.lang.String
	 * @author nianhua.jiang
	 * @date 2020/5/25 15:13
	 */
	@Override
	public String getCode() {
		boolean flg = true;
		String code = "";
		while (flg) {
			//随机6位机构码
			code = (int) ((Math.random() * 9 + 1) * 100000) + "";
			//判断机构码是否重复
			OrganizationCommon org = organizationCommonMapper
					.selectOne(Wrappers.<OrganizationCommon>query().lambda().eq(
							OrganizationCommon::getCode, code));

			//不存在机构码，跳出循环
			if (org == null) {
				flg = false;
			}
		}
		//返回随机生成的机构码
		return code;
	}

	/**
	 * 生成用户唯一账户ID
	 *
	 * @param
	 * @return java.lang.String
	 * @author nianhua.jiang
	 * @date 2020/6/23 14:15
	 */
	@Override
	public String getAccount() {

		boolean flg = true;
		String code = "";
		while (flg) {

			//随机9位数字作为其账户ID
			code = (int) ((Math.random() * 9 + 1) * 1000000) + "";
			//判断账户ID是否重复
			List<Member> account = memberMapper
					.selectList(new QueryWrapper<Member>().eq("account", code));

			//不存在机构码，跳出循环
			if (account.size() == 0) {
				flg = false;
			}
		}
		//返回随机生成的账户ID
		return code;
	}

	private String checkIfClaimedAlready(
			Map returnMap, String memberId, Integer rewardId, Member member, String type) {
		String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String concatKey = dateString + memberId + "_" + rewardId;
		//用来验证是否今日奖励是否领取过
		Boolean setSuccess = redisTemplate.opsForValue().setIfAbsent(
				concatKey, false, 86400, TimeUnit.SECONDS);

		if (!setSuccess) {
			//false表示key已存在，不能在被领取
			returnMap.put("result", false);
			returnMap.put(type, member.getExp());
			returnMap.put("delta", 0);
			returnMap.put("info", "今日已领取过该奖励，不能重复领取！");
		}

		returnMap.put("result", true);

		return concatKey;
	}

	private Map getMemberClaimInfo() {
		Map returnMap = new HashMap();
		List readyForClaim = new ArrayList();
		List claimed = new ArrayList();
		String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		String memberId = SecurityUtils.getMember().getId();
		Member member = this.getById(memberId);
		List<SmMemberPlayRewardInfo> rewardInfoList = this.getRewardInfo();

		StudentPlayTimeDaily playTimeDaily = this.getPlayTimeDaily(
				memberId, dateString);
		Integer playTime = playTimeDaily == null ? 0 : playTimeDaily.getPlayTime();

		for (int i = 0; i < rewardInfoList.size(); i++) {
			Integer tempRewardId = rewardInfoList.get(i).getId();
			String concatKey = dateString + memberId + "_" + tempRewardId;

			Object obj = redisTemplate.opsForValue().get(concatKey);
			if (obj != null) {
				claimed.add(tempRewardId);
			} else if (obj == null
					//分钟换算成秒
					&& playTime >= (rewardInfoList.get(i).getDuration() * 60)) {
				readyForClaim.add(tempRewardId);
			}
		}

		returnMap.put("readyForClaim", readyForClaim);
		returnMap.put("claimed", claimed);
		returnMap.put("points", member.getPoints());
		returnMap.put("exp", member.getExp());
		returnMap.put("playTimeToday", playTime);

		return returnMap;
	}

	@Override
	public String getSyMemberCount(int day, String isOld) {

		//查询当前周上音社注册数量
		LocalDate date = LocalDate.now();
		//计算今天是周几
		long weekValue = date.getDayOfWeek().getValue();
		//计算本周末是几号(判断小于，所以往后一位)
		LocalDate weekendNow = date.plusDays(8 - weekValue);

		LocalDate endTime = weekendNow.plusWeeks(-1 * (day - 1));

		//计算本周周一是几号
		LocalDate startTime = endTime.plusDays(-7);

		Integer count = 0;

		if (!"999".equals(isOld)) {

			if ("998".equals(isOld)) {

				count = memberActivateMapper.selectCount(new QueryWrapper<MemberActivateEntity>()
						.gt("create_time", startTime.toString())
						.lt("create_time", endTime.toString()));

			} else {
				count = memberMapper.selectCount(new QueryWrapper<Member>()
						.eq("is_old", isOld)
						.gt("create_time", startTime.toString())
						.lt("create_time", endTime.toString()));
			}

		} else {
			count = memberMapper.selectCount(new QueryWrapper<Member>()
					.ne("is_old", "1")
					.gt("create_time", startTime.toString())
					.lt("create_time", endTime.toString()));
		}

		return count.toString();

	}

	@Override
	public String getNewMemberHardwareCount(int day) {

		LocalDate date = LocalDate.now();
		//计算今天是周几
		long weekValue = date.getDayOfWeek().getValue();
		//计算本周末是几号(判断小于，所以往后一位)
		LocalDate weekendNow = date.plusDays(8 - weekValue);

		LocalDate endTime = weekendNow.plusWeeks(-1 * (day - 1));

		//计算本周周一是几号
		LocalDate startTime = endTime.plusDays(-7);

		Integer count = 0;

		List<Member> memberNew = memberMapper.selectList(new QueryWrapper<Member>()
				.eq("is_old", "3")
				.or().eq("is_old", "0"));

		for (Member member : memberNew) {

			List<MemberActivateEntity> memberActivateEntities = memberActivateMapper
					.selectList(new QueryWrapper<MemberActivateEntity>()
							.eq("member_id", member.getId())
							.gt("create_time", startTime.toString())
							.lt("create_time", endTime.toString())
							.orderByDesc("start_time"));

			if (memberActivateEntities.size() > 0) {
				if (memberActivateEntities.stream().anyMatch(x -> x.getDuration() == 0)) {
					count++;
					continue;
				}

				if (memberActivateEntities.get(0).getStartTime()
						.plusDays(memberActivateEntities.get(0).getDuration())
						.isAfter(LocalDateTime.now())) {
					count++;
					continue;
				}
			}

		}

		return count.toString();

	}

	@Override
	public boolean rollbackVip(String memberId, Integer duration) {

		//判断此用户目前的 VIP 时长是否大于 duration
		List<MemberRole> roles = memberRoleMapper.getRole(memberId);

		if (roles == null) {
			//会员已过期
		} else {
			//业务只能查询出来一条数据
			MemberRole memberRole = roles.get(0);
			//用户会员到期时间
			LocalDateTime endTime = memberRole.getEndTime();

			if (LocalDateTime.now().plusDays(30).isAfter(endTime)
					|| LocalDateTime.now().plusDays(30).equals(endTime)) {
				//设置过期时间为当前时间
				memberRole.setEndTime(LocalDateTime.now());
			} else {
				//设置过期时间为 {duration}天之前
				LocalDateTime endTimeNew = endTime.minusDays(duration);
				memberRole.setEndTime(endTimeNew);
			}
			memberRoleMapper.updateById(memberRole);
		}
		return true;
	}

	@Override
	public boolean rollbackMaster(String memberId, Integer duration) {

		//查询会员是否已经激活，如果已经激活，返回还剩多长时间过期
		R status = remoteOrganService.isMaster(memberId);
		Map statusMap = (Map) status.getData();

		//查询会员激活记录
		//status: 0-未激活, 1-已激活, 2-已过期
		if ((int) statusMap.get("status") == 1) {

			// 计算到期时间
			List<MemberActivateEntity> activateEntities = memberActivateMapper
					.selectList(new QueryWrapper<MemberActivateEntity>()
							.eq("member_id", memberId)
							.orderByDesc("start_time"));

			if (activateEntities.stream().anyMatch(x -> x.getDuration() == 0)) {
				//永久权限，无须回退
				return true;
			}

			//循环取到期时间最后的
			LocalDateTime endTime = activateEntities.get(0).getStartTime()
					.plusDays(activateEntities.get(0).getDuration());

			for (MemberActivateEntity memberActivateEntity : activateEntities) {
				//循环取到期时间最后的
				if (endTime.isBefore(memberActivateEntity.getStartTime()
						.plusDays(memberActivateEntity.getDuration()))) {
					endTime = memberActivateEntity.getStartTime()
							.plusDays(memberActivateEntity.getDuration());
				}
			}

			MemberActivateEntity memberActivateEntity = activateEntities.get(0);

			//到期时间大于{duration}天，直接扣除{duration}天
			if (endTime.isAfter(LocalDateTime.now().plusDays(duration))) {
				memberActivateEntity.setDuration(memberActivateEntity.getDuration() - duration);
			}

			//到期时间小于{duration}天，开始时间设置为昨天，时长为1天
			else {
				memberActivateEntity.setStartTime(LocalDateTime.now().minusDays(1));
				memberActivateEntity.setDuration(1);
			}

			memberActivateMapper.updateById(memberActivateEntity);

		}
		return true;
	}

	@Override
	public IPage<MidoUserDataVO> getMidoUser(Page page, String username) {

		//获取 mido 用户基础信息数据
		IPage<MidoUserDataVO> midoUserPage = memberMapper.getMidoUser(page, username);

		List<MidoUserDataVO> midoUsers = midoUserPage.getRecords();

		for (MidoUserDataVO midoUser : midoUsers) {

			//硬件权限
			List<MidoMasterDTO> midoMasterDTOS = memberActivateMapper
					.getMidoMaster(midoUser.getMemberId());

			//无硬件权限
			if (CollectionUtils.isEmpty(midoMasterDTOS)) {
				midoUser.setIsMaster("0");
				continue;
			}

			//有硬件权限，判断是否到期
			else {

				//激活码
				if (midoMasterDTOS.stream().anyMatch(x -> x.getDuration() == 0)) {
					//永久权限
					midoUser.setIsMaster("1");
					midoUser.setMasterDuration(0);
					//硬件权限开通时间
					midoUser.setMasterCreateTime(midoMasterDTOS.get(0).getStartTime());
					//激活码
					midoUser.setAtvCode(midoMasterDTOS.get(0).getAtvCode());
					continue;
				}

				//计算到期时间
				LocalDateTime endTime = midoMasterDTOS.get(0).getStartTime()
						.plusDays(midoMasterDTOS.get(0).getDuration());

				int duration = 0;
				for (MidoMasterDTO midoMasterDTO : midoMasterDTOS) {
					duration += midoMasterDTO.getDuration();
					//循环取到期时间最后的
					if (endTime.isBefore(
							midoMasterDTO.getStartTime().plusDays(midoMasterDTO.getDuration()))) {
						endTime = midoMasterDTO.getStartTime()
								.plusDays(midoMasterDTO.getDuration());
					}
				}

				//判断 endTime 和今天日期,是否到期
				if (endTime.isAfter(LocalDateTime.now())) {
					midoUser.setIsMaster("1");
					midoUser.setMasterCreateTime(midoMasterDTOS.get(0).getStartTime());
					midoUser.setMasterDuration(duration);
					//激活码
					midoUser.setAtvCode(midoMasterDTOS.get(0).getAtvCode());
				} else {
					//已过期
					midoUser.setIsMaster("2");
					//激活码
					midoUser.setAtvCode(midoMasterDTOS.get(0).getAtvCode());
				}
			}
		}
		midoUserPage.setRecords(midoUsers);
		return midoUserPage;
	}

	@Override
	public IPage<MidoOrgVO> getMidoOrgPage(Page page, String code) {
		return memberMapper.getMidoOrgPage(page, code);
	}

	@Override
	public List<String> getStudentIdsByMemberId(String memberId) {
		return memberMapper.getStudentIdsByMemberId(memberId);
	}

	@Override
	public IPage<OptOperatorOldVO> getOpt(Page page, String name, String username) {
		return memberMapper.getOpt(page, name, username);
	}

	@Override
	public List<MidoOrganOldVO> getOrgList(String optId, String word) {
		return memberMapper.getOrgList(optId, word);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean delMember(String phone, String isTeacher, String teacherId, String studentId) {

		//判断账号是否是 运营商 创建人员
		List<OptOperator> optOperators = memberMapper.getOptListByPhone(phone);
		//判断账号是否是 机构（非工作室） 创建人员
		List<OrgOrganization> orgOrganizations = memberMapper.getOrgListByPhone(phone);

		if (CollectionUtils.isNotEmpty(optOperators)) {
			throw new BusinessException("您的账号已创建运营商，如需注销请联系总部");
		}

		if (CollectionUtils.isNotEmpty(orgOrganizations)) {
			throw new BusinessException("您的账号已创建机构，如需注销请联系总部");
		}

		String memberId = SecurityUtils.getMember().getId();

		//教师身份/学生身份 验证绑定关系 需解绑之后才能注销账号
		//教师身份
		if ("1".equals(isTeacher)) {

			//查看是否有关联的学生
			if (StringUtils.isEmpty(teacherId)) {
				throw new BusinessException("教师身份的场合，教师ID不能为空");
			}

			OrgTeacherDetailed orgTeacherDetailed = teacherDetailedMapper.selectById(teacherId);

			if (orgTeacherDetailed == null) {
				throw new BusinessException("教师信息不存在");
			}

			Integer studentCount = teacherStudentMapper.selectCount(new QueryWrapper<OrgTeacherStudent>().eq("teacher_id", teacherId));
			if (studentCount > 0) {
				throw new BusinessException("您已绑定学生，请解绑后再试");
			}

			Integer classTeacherCount = classTeacherMapper
					.selectCount(new QueryWrapper<MultiTeacherClassroomLink>().eq("teacher_id", teacherId));
			if (classTeacherCount > 0) {
				throw new BusinessException("您还在班级中，请先退出班级");
			}

			// 清除 sm_member 数据
			memberMapper.delete(new QueryWrapper<Member>().eq("username", phone));
			// 清除 sys_user 数据
			memberMapper.deleteSysUser(phone);
			// 清除 org_organization 数据
			organizationCommonMapper.deleteById(orgTeacherDetailed.getOrgId());
			// 清除 org_teacher_detailed 数据
			teacherDetailedMapper.deleteById(orgTeacherDetailed.getId());
			// 清除 sm_member_teacher_approval_new 数据
			teacherApprovalMapper
					.delete(new QueryWrapper<SmMemberTeacherApprovalNew>().eq("member_id", orgTeacherDetailed.getMemberId()));

		}
		//学生身份
		else {

			//查看是否有关联的教师
			if (StringUtils.isEmpty(studentId)) {
				throw new BusinessException("学生身份的场合，studentId不能为空");
			}

			OrgStudentDetailed studentDetailed = studentMapper.selectById(studentId);

			if (studentDetailed == null) {
				throw new BusinessException("学生信息不存在");
			}

			Integer studentCount = teacherStudentMapper.selectCount(new QueryWrapper<OrgTeacherStudent>().eq("student_id", studentId));
			if (studentCount > 0) {
				throw new BusinessException("您已绑定老师，请解绑后再试");
			}

			Integer classStudentCount = classStudentMapper
					.selectCount(new QueryWrapper<MultiStudentClassroomLink>().eq("student_id", studentId));
			if (classStudentCount > 0) {
				throw new BusinessException("您还在班级中，请先退出班级");
			}

			// 清除 sm_member 数据
			memberMapper.delete(new QueryWrapper<Member>().eq("username", phone));
			// 清除 org_student_detailed 数据
			studentMapper.delete(new QueryWrapper<OrgStudentDetailed>().eq("member_id", studentDetailed.getMemberId()));

		}
		redisTemplate.delete("delMember_" + memberId + "_startTime");
		redisTemplate.delete("delMember_" + memberId + "_endTime");

		//统计注销用户
		SmMemberDel smMemberDel = new SmMemberDel();
		smMemberDel.setCreateTime(LocalDateTime.now());
		smMemberDel.setUsername(phone);
		delLogMapper.insert(smMemberDel);

		return true;
	}

	@Override
	public Map<String, String> saveDelMemberLog(String memberId, Integer dayCount) {

		String startTime = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());

		String endTime = String.valueOf(LocalDateTime.now().plusDays(dayCount).toInstant(ZoneOffset.of("+8")).toEpochMilli());

		redisTemplate.opsForValue().set("delMember_" + memberId + "_startTime", startTime, 30, TimeUnit.DAYS);
		//TODO
		redisTemplate.opsForValue().set("delMember_" + memberId + "_endTime", endTime, 30, TimeUnit.DAYS);

		Map<String, String> resMap = new HashMap<>(2);
		resMap.put("startTime", startTime);
		resMap.put("endTime", endTime);
		return resMap;
	}

	private String addMsg(String title, String message, String regId, String pushRespCode,
			String pushRespMsg, String triggerTo) {

		MsgMain msgMain = new MsgMain();
		//给教师发送
		msgMain.setTriggerTo(triggerTo);
		//来自师生绑定/解绑 - 系统自动推送
		msgMain.setTriggerFrom("0");
		//消息下发的场合：师生关系
		msgMain.setPoint("5");
		//不可修改
		msgMain.setModify("0");
		//自动推送
		msgMain.setMode("1");
		//个人
		msgMain.setRangeType("1");
		//有效数据
		msgMain.setDelFlag("0");
		//创建时间
		msgMain.setCreateTime(LocalDateTime.now());
		//消息类型：文本
		msgMain.setMsgType("0");
		//发送时间
		msgMain.setActualPubDatetime(LocalDateTime.now());
		//创建人-> 系统
		msgMain.setCreateUser("sys");
		//消息内容
		msgMain.setMessage(message);
		//发布时间
		msgMain.setPubDatetime(LocalDateTime.now());
		//极光推送唯一ID
		msgMain.setPushId(regId);
		//极光推送返回 code
		msgMain.setPushRespCode(pushRespCode);
		//极光推送返回 msg
		msgMain.setPushRespMsg(pushRespMsg);
		//TODO 推送成功
		msgMain.setPushStatus("0");
		//推送时间
		msgMain.setPushTime(LocalDateTime.now());
		//标题
		msgMain.setTitle(title);
		//家校消息
		msgMain.setType("1");

		return msgMainService.addSysMsg(msgMain);
	}

}
